<?php

include_once 'common.php';

$filter = ' WHERE ';
if ($payload && count($payload) > 0) {
  foreach ($payload as $item) {
    if (is_array($item->value)) {
      // item:{key:office,value:['管制一室','管制二室']}
      if (count($item->value) > 0) {
        $str = " ' " . implode(" ',' ", $item->value) . " ' ";
        $filter .= $item->key . " IN '(" . $str . "') AND ";
      }
    } elseif (is_object($item->value)) {
      // item:{key:'date',symbol:'>=',value:'2020-01-01'}
      if ($item->value->value != '' && $item->value->value != 0) {
        $filter .= $item->key . " " . $item->value->symbol . " '" . $item->value->value . "' AND ";
      }
    } else {
      if ($item->value != '' && $item->value != null) {
        $filter .= $item->key . " = '" . $item->value . "' AND ";
      }
    }
  }
  $filter = substr($filter, 0, -5);
}
if ($filter == ' WHERE ') {
  $filter .= ' 1';
}

$sql = "SELECT * FROM `trex_exercises` {$filter} ORDER BY `updateTime` DESC";
$result = exec_sql($sql);
if (!$result || count($result) == 0) {
  output([]);
} else {
  foreach ($result as $key => $value) {
    $result[$key]['subjects'] = json_decode($value['subjects']);
  }
  output($result);
}
